package com.daoliuhe.scaffold.service.impl;

import com.daoliuhe.scaffold.mapper.AuthoritiesMapper;
import com.daoliuhe.scaffold.model.Authorities;
import com.daoliuhe.scaffold.service.AuthoritiesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AuthoritiesServiceImpl implements AuthoritiesService {

    private static final Logger logger = LoggerFactory.getLogger(AuthoritiesServiceImpl.class);

    @Autowired
    AuthoritiesMapper authoritiesMapper;

    @Override
    public Authorities getById(String id) {
        logger.info("getById,id:{}", id);
        Authorities u = authoritiesMapper.selectByPrimaryKey(id);
        u.setProductLineStr(u.getProductLineStr());
        return u;
    }

    @Override
    public void saveOrUpdate(Authorities auth) {
        logger.info("saveOrUpdate,auth:{}", auth);
        if (!StringUtils.isEmpty(auth.getId())) {
            authoritiesMapper.updateByPrimaryKey(auth);
        } else {
            authoritiesMapper.insert(auth);
        }
    }

    @Override
    public Map<String, Object> getPageData(Authorities auth) {
        logger.info("getPageData,auth:{}", auth);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", authoritiesMapper.getPageCount(auth));
        map.put("rows", authoritiesMapper.getPageData(auth));
        return map;
    }

    @Override
    public boolean isRightApi(String permission, String id) {
        logger.info("isRightApi,permission:{},id:{}", permission, id);
        boolean flag = false;
        if (StringUtils.isEmpty(id)) {
            flag = authoritiesMapper.selectByName(permission) == null;
        } else {
            Authorities auth = authoritiesMapper.selectByPrimaryKey(id);
            if (auth != null) {
                flag = auth.getPermission().equals(permission);
                if (!flag) {
                    flag = authoritiesMapper.selectByName(permission) == null;
                }
            }
        }
        return flag;
    }


    @Override
    public List<Authorities> getAuthoritiesList(Authorities auth) {
        logger.info("getAuthoritiesList,auth:{}", auth);
        return authoritiesMapper.getPageData(auth);

    }

}
